import CAS from './CAS.js'
import store from '../store'
import router from '../router'
import MessageUtil from '../utils/MessageUtil'
import LocaleUtil from "../utils/LocaleUtil";
import Vue from "vue";
import {OSS_CURRENT_CALLBACK_URL} from "../store/mutation-types";

// 开启单点之后，需要关闭的页面
const closedList = ['/index/login', '/index/register', '/index/register-result', '/index/alteration']

export const SSO = {
  /**
   * 路由拦截到的入口方法
   * @param path
   * @param next
   * @param currentPath
   */
  redirectUrl(path, next, currentPath) {
    if (closedList.indexOf(path) !== -1 && bootConfig[process.env.NODE_ENV].VUE_APP_SSO === "cas") {
      // 基于cas的单点登录
      CAS.casLogin(next)
    } else if (closedList.indexOf(path) !== -1 && bootConfig[process.env.NODE_ENV].VUE_APP_SSO === "oauth2") {
      // 基于oauth2的单点登录
      this.validOauth2(currentPath)
    } else {
      const code = SSO.getQueryString("code")
      const dingAppId = bootConfig[process.env.NODE_ENV].VUE_APP_DINGTALK_APP_KEY;
      if (code && dingAppId) {
        // 钉钉扫码登录，去后台获取token
        this.loginByDingtalk(code);
        return
      }
      // 默认
      next()
    }
  },
  /**
   * 通过Oauth2验证是否已经登录
   * @param currentPath
   */
  validOauth2(currentPath) {
    if (!bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_URL
      || !bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_CLIENT_ID
      || !bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_SCOPE) {
      MessageUtil.warning(LocaleUtil.getLocale('m.system.login.other.sso_null'))
      return;
    }
    const code = SSO.getQueryString("code")
    if (code) {
      // 去后台获取token
      this.loginByOauth2(code);
    } else {
      // 跳转单点登录页面
      this.redirectOauth2(currentPath);
    }
  },
  /**
   * 得到code之后，去后台获取token，执行本平台的登录逻辑
   * @param code 得到的验证码
   */
  loginByOauth2(code) {
    store.dispatch('Oauth2Login', {code: code}).then((res) => {
      const currentPath = Vue.ls.get(OSS_CURRENT_CALLBACK_URL);
      if (currentPath) {
        router.push({path: currentPath})
      } else {
        router.push({path: '/'})
      }
    }).catch((err) => {
      //console.log(err)
      MessageUtil.warning(((err.response || {}).data || {}).message || err.message || LocaleUtil.getLocale('m.system.login.other.loginError'), LocaleUtil.getLocale('m.system.login.other.loginFailed'))
      const that = this
      setTimeout(function () {
        that.logoutByOauth2()
      }, 1500)
    })
  },
  /**
   * 退出Oauth2单点
   */
  logoutByOauth2() {
    const protocolAndPath = window.location.protocol + '//' + window.location.host + process.env.BASE_URL;
    let callbackUrl = protocolAndPath;
    callbackUrl = callbackUrl.replace("localhost", "127.0.0.1");
    let url = bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_URL;
    url += (bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_LOGOUT || '/logout')
    url += "?redirect_uri=" + callbackUrl;
    window.location.href = url;
  },
  /**
   * 跳转Oauth2登录页面，携带参数
   * @param currentPath
   */
  redirectOauth2(currentPath) {
    const protocolAndPath = window.location.protocol + '//' + window.location.host + process.env.BASE_URL;
    let callbackUrl = protocolAndPath;
    callbackUrl = callbackUrl.replace("localhost", "127.0.0.1");
    let url = bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_URL;
    url += (bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_AUTHORIZE || '/oauth2/authorize')
    url += "?response_type=code";
    url += "&client_id=" + (bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_CLIENT_ID);
    url += "&scope=" + (bootConfig[process.env.NODE_ENV].VUE_APP_OAUTH2_SCOPE || '');
    url += "&redirect_uri=" + callbackUrl; // 服务端必须授权

    // 缓存当前地址，单点成功后，再回到当前地址
    if (currentPath) {
      Vue.ls.set(OSS_CURRENT_CALLBACK_URL, currentPath, 10 * 1000) // 10秒
    }
    window.location.href = url
  },
  /**
   * 得到code之后，去后台获取token，执行本平台的登录逻辑
   * @param code 得到的验证码
   */
  loginByDingtalk(code) {
    store.dispatch('DingtalkLogin', {code: code}).then((res) => {
      router.push({path: '/'})
    }).catch((err) => {
      //console.log(err)
      MessageUtil.warning(((err.response || {}).data || {}).message || err.message || LocaleUtil.getLocale('m.system.login.other.loginError'), LocaleUtil.getLocale('m.system.login.other.loginFailed'))
      setTimeout(function () {
        window.location.href = window.location.protocol + '//' + window.location.host + process.env.BASE_URL;
      }, 1500)
    })
  },
  /**
   * 使用钉钉扫码登录
   */
  useDingtalk() {
    const protocolAndPath = window.location.protocol + '//' + window.location.host + process.env.BASE_URL;
    let callbackUrl = protocolAndPath;
    const dingAppId = bootConfig[process.env.NODE_ENV].VUE_APP_DINGTALK_APP_KEY;
    if (!dingAppId) {
      MessageUtil.warning(LocaleUtil.getLocale('m.system.login.other.ding_null'))
      return
    }
    let url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${dingAppId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${callbackUrl}`
    let goto = encodeURIComponent(url)
    const obj = this.DDLogin({
      id: "login_container",//这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
      goto: goto, //请参考注释里的方式
      style: "border:none;background-color:#FFFFFF;",
      width: "365",
      height: "300"
    });
    const handleMessage = function (event) {
      const origin = event.origin;
      if (origin === "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
        const loginTmpCode = event.data;
        window.location.href = url + `&loginTmpCode=${loginTmpCode}`
      }
    };
    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onmessage', handleMessage);
    }
  },
  /**
   * 钉钉扫码登录框，来自钉钉文档
   * @param a
   * @constructor
   */
  DDLogin(a) {
    let e, c = document.createElement("iframe"),
      d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto;
      d += a.style ? "&style=" + encodeURIComponent(a.style) : "",
      d += a.href ? "&href=" + a.href : "",
      c.src = d,
      c.frameBorder = "0",
      c.allowTransparency = "true",
      c.scrolling = "no",
      c.width = a.width ? a.width + 'px' : "365px",
      c.height = a.height ? a.height + 'px' : "400px",
      e = document.getElementById(a.id),
      e.innerHTML = "",
      e.appendChild(c)
  },
  /**
   * 从浏览器URL中获取指定参数的值
   * @param name 参数名
   * @returns {string} 参数值
   */
  getQueryString(name) {
    const url_string = window.location.href
    const url = new URL(url_string);
    return url.searchParams.get(name);
  },
};
